import { useLoader } from '@react-three/fiber'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import { Mesh } from 'three'
import { useEffect, useRef } from 'react'
import type { FC } from 'react'

interface ModelLoaderProps {
  url: string
  scale?: number
  position?: [number, number, number]
  rotation?: [number, number, number]
  onLoad?: () => void
  onError?: (error: Error) => void
}

// 初始化Draco解码器
const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath('/draco/') // 需要将draco文件复制到public目录

// 配置GLTF加载器
const gltfLoader = new GLTFLoader()
gltfLoader.setDRACOLoader(dracoLoader)

const ModelLoader: FC<ModelLoaderProps> = ({
  url,
  scale = 1,
  position = [0, 0, 0],
  rotation = [0, 0, 0],
  onLoad,
  onError
}) => {
  const modelRef = useRef<Mesh>(null)
  
  const gltf = useLoader(GLTFLoader, url, (loader) => {
    loader.setDRACOLoader(dracoLoader)
  })

  useEffect(() => {
    if (gltf) {
      try {
        // 模型加载后的处理
        if (modelRef.current) {
          modelRef.current.traverse((child) => {
            if ((child as Mesh).isMesh) {
              // 启用阴影
              child.castShadow = true
              child.receiveShadow = true
            }
          })
        }
        onLoad?.()
      } catch (error) {
        onError?.(error as Error)
      }
    }
  }, [gltf, onLoad, onError])

  return (
    <primitive
      ref={modelRef}
      object={gltf.scene}
      scale={scale}
      position={position}
      rotation={rotation}
    />
  )
}

export default ModelLoader 